package com.rabbitmq.RabbitMQ;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.Entity.RabbitMQ;
import com.rabbitmq.Entity.RabbitMQInfo;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class RabbitMQSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendString() {
        String context = "Hello World!";
        System.out.println("MQSender发送内容:" + context);
        this.rabbitTemplate.convertAndSend(RabbitMQ.EXCHANGE,RabbitMQ.ROUTINGKEY_HELLOTOSTRING, context, new CorrelationData(UUID.randomUUID().toString()));
        System.out.println("MQSender发送时间:" +  new Date());
    }

    public void sendObj() {
        RabbitMQInfo rabbit = new RabbitMQInfo("localhost","5672","guest","guest",null);
        System.out.println("MQSender发送内容:" + JSON.toJSONString(rabbit));
        this.rabbitTemplate.convertAndSend(RabbitMQ.EXCHANGE,RabbitMQ.ROUTINGKEY_HELLOOBJ, rabbit, new CorrelationData(UUID.randomUUID().toString()));
        System.out.println("MQSender发送时间:" +  new Date());
    }

    public void sendDelay() {
        RabbitMQInfo rabbit = new RabbitMQInfo("localhost","5672","guest","guest",null);
        System.out.println("MQSender发送内容:" + JSON.toJSONString(rabbit));
        this.rabbitTemplate.convertAndSend(RabbitMQ.EXCHANGE_DELAY, RabbitMQ.ROUTINGKEY_DELAY, rabbit, message -> {
            // TODO 第一句是可要可不要,根据自己需要自行处理
            message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, RabbitMQInfo.class.getName());
            // TODO 如果配置了 params.put("x-message-ttl", 5 * 1000); 那么这一句也可以省略,具体根据业务需要是声明 Queue 的时候就指定好延迟时间还是在发送自己控制时间
            message.getMessageProperties().setExpiration(5 * 1000 + "");
            return message;
        }, new CorrelationData(UUID.randomUUID().toString()));
        System.out.println("MQSender发送时间:" +  new Date());
    }

}